#!/usr/bin/env python
# -*- coding:utf-8 -*-
import json

from sqlalchemy import desc

from controller.apiKeyController import ApiKeyController
from models import db
from models.api_key import ApiKey
from models.sso_user import SsoUser
from utils import commons
from utils.loggings import loggings
from utils.response_code import RET
from utils.rsa_encryption_decryption import RSAEncryptionDecryption


class ApiKeyService(ApiKeyController):

    @classmethod
    def add_api_key(cls, **kwargs):
        """
            添加api key
        """
        # check settings format
        try:
            settings = kwargs.get('settings')
            if settings:
                json.loads(settings)
        except Exception as e:
            return {'code': 400, 'message': 'settings format error', 'data': {'error': str(e)}}

        from utils.generate_id import GenerateID
        key_id = GenerateID.create_random_id()

        try:
            db.session.begin_nested()
            api_key_model = ApiKey(
                key_id=key_id,
                user_id=kwargs.get('user_id'),
                content=RSAEncryptionDecryption.encrypt(kwargs.get('content')) if kwargs.get('content') else None,
                settings=kwargs.get('settings'),
                chat_model=kwargs.get('chat_model'),
            )
            db.session.add(api_key_model)

            from flask import g

            filter_list = [SsoUser.is_deleted == 0, SsoUser.user_id == g.user['user_id']]
            res = db.session.query(SsoUser).filter(*filter_list).with_for_update()
            res.update({'key_id': key_id})
            db.session.commit()

        except Exception as e:
            db.session.rollback()
            loggings.exception(1, e)
            return {'code': RET.DATAERR, 'message': 'add api key error', 'data': {'error': str(e)}}

        return {'code': RET.OK, 'message': 'add api key success', 'data': {'key_id': key_id}}

    @classmethod
    def change_current_api_key(cls, key_id):
        """
            切换用户当前api key
        """
        try:
            from flask import g
            filter_list = [SsoUser.is_deleted == 0, SsoUser.user_id == g.user['user_id']]
            res = db.session.query(SsoUser).filter(*filter_list).with_for_update()
            res.update({'key_id': key_id})
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            loggings.exception(1, e)
            return {'code': RET.DATAERR, 'message': 'change current api key error', 'data': {'error': str(e)}}

        return {'code': RET.OK, 'message': 'change current api key success', 'data': {'key_id': key_id}}

    @classmethod
    def delete_api_key(cls, key_id):
        """
            删除用户当前api key
        """
        try:
            db.session.begin_nested()
            filter_list = [ApiKey.is_deleted == 0, ApiKey.key_id == key_id]
            res = db.session.query(ApiKey).filter(*filter_list).with_for_update()
            res.update({'is_deleted': 1})

            from flask import g
            filter_list = [SsoUser.is_deleted == 0, SsoUser.user_id == g.user['user_id']]
            res = db.session.query(SsoUser).filter(*filter_list).with_for_update()
            res.update({'key_id': None})
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            loggings.exception(1, e)
            return {'code': RET.DATAERR, 'message': 'delete current api key error', 'data': {'error': str(e)}}

        return {'code': RET.OK, 'message': 'delete current api key success', 'data': {'user_id': g.user['user_id']}}

    @classmethod
    def get_current_model(cls):
        """
            获取当前模型
        """
        from flask import g
        filter_list = [SsoUser.is_deleted == 0, SsoUser.user_id == g.user['user_id']]
        user = db.session.query(SsoUser).filter(*filter_list).first()

        if not user:
            return {'code': RET.DATAERR, 'message': 'get current model error', 'data': {'error': 'user not found'}}
        res = db.session.query(ApiKey).filter(ApiKey.key_id == user.key_id).first()
        if not res:
            return {'code': RET.DATAERR, 'message': 'get current model error', 'data': {'error': 'api key not found'}}
        return {'code': RET.OK, 'message': 'get current model success', 'data': {'chat_model': res.chat_model, 'key_id': res.key_id}}

    @classmethod
    def get_api_key_list(cls):
        """
            获取用户api key列表
        """
        from flask import g
        user_id = g.user['user_id']
        filter_list = [ApiKey.is_deleted == 0, ApiKey.user_id == user_id]
        res = db.session.query(ApiKey).order_by(desc(ApiKey.update_time)).filter(*filter_list).all()
        if not res:
            return {'code': RET.DATAERR, 'message': 'get api key list error', 'data': {'error': 'api key not found'}}
        results = commons.query_to_dict(res)
        return {'code': RET.OK, 'message': 'get api key list success', 'data': results}
